function ecog = ecogFindTrough(ecog, band, signaltype)

% INPUT: ecog structure and the number of the band according to the order
%        in ecog.BPdata. 
%        theta      ==> 1;
%        lowalpha   ==> 2;
%        hialpha    ==> 3;
%        beta       ==> 4;
%        gamma      ==> 5;
%        higamma    ==> 6;
%
% OUTPUT: ecog structure with a new field called troughs, which is a cell 
%         array containing the time points of the troughs found in the 
%         frequency bands specified by band. 
% 
% EXAMPLE: ecog = ecogFindTrough(ecog,1)
%          for theta troughs
%          
% NOTE: use ecogBandpassFilter before finding the troughs.  
%       Afterwards ecogValidTroughs.m can be used for detection of troughs 
%       after a certain stimulus or event

if isfield(ecog,'troughs') == 1;
    ecog = rmfield(ecog,'troughs');
end


clc;

switch signaltype;
    case 'timeseries'
        for k = 1:size(band,2)
        for chan = 1:size(ecog.data,1);
            sig = ecog.BPdata{band(k)}(chan,:);
            hilsig = hilbert(sig);
            angsig = angle(hilsig);
            minvals = find(angsig < -pi + .01);
            d = diff(minvals);
            idx = find(d > 1);
            minvals = minvals(idx);
            ecog.troughs{band(k)}(chan,1:length(minvals)) = minvals;

        %     d = sign(diff(ecog.BPdata{band}(chan,:)));
        %     minvals = find(d > [d(1) d(1:end-1)]); 
        %     ecog.troughs{band}(chan,1:length(minvals)) = minvals;
        end
        end

    case 'trial'
        for k = 1:size(band,2);
        for trial = 1:size(ecog.BPdata{band(k)},3);
        for chan = 1:size(ecog.data,1);
            sig = ecog.BPdata{band(k)}(chan,:,trial);
%             hilsig = hilbert(sig);
%             angsig = angle(hilsig);
%             minvals = find(angsig < -pi  + .01);
%             d = diff(minvals);
%             idx = find(d > 1);
%             minvals = minvals(idx);

            d = sign(diff(sig));
            minvals = find(d > [d(1) d(1:end-1)]);
%             x = find(sig(minvals) < mean(sig) - std(sig));
%             minvals = minvals(x);
            ecog.troughs{band(k)}(chan,1:length(minvals),trial) = minvals;
        end
        end
        end  
end